/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
*   Nick Kreeger
* Portions created by the Initial Developer are Copyright (C) 2006-2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*   Nick Kreeger <nick.kreeger@park.edu>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */

#import "MessageAccountManager.h"
#import "MessageAccount.h"
#import "MessageWindowService.h"
#import "NSString+Utils.h"
#import "CHISupportsOwner.h"

#import "nsCOMPtr.h"
#import "nsIMsgIdentity.h"
#import "nsIMsgIncomingServer.h"
#import "nsIMsgAccountManager.h"
#import "nsIMessengerMigrator.h"
#import "nsIMsgWindow.h"
#import "nsISmtpService.h"
#import "nsISmtpServer.h"

#import "nsMsgBaseCID.h"
#import "nsMsgCompCID.h"

NSString* const kAccountRegistryChanged = @"AccountRegistryChanged";

@interface MessageAccountManager(Private)

-(const char*)literalForServerType:(EAccountType)aServerType;

@end

@implementation MessageAccountManager

static MessageAccountManager* sInstance = nil;

+(id)sharedInstance
{
  return (sInstance ? sInstance : sInstance = [[self alloc] init]);
}

-(BOOL)getAccounts:(nsISupportsArray**)inSupportsArray;
{
  NS_ENSURE_ARG_POINTER(inSupportsArray);
  
  nsresult rv;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, NO);
  
  nsCOMPtr<nsISupportsArray> accounts;
  rv = accountManager->GetAccounts(getter_AddRefs(accounts));
  NS_ENSURE_SUCCESS(rv, NO);
  
  NS_ADDREF(*inSupportsArray = accounts);
  
  return YES;
}

-(BOOL)accountsExist
{  
  nsresult rv;
  BOOL shouldUpdatePrefs = NO;
  BOOL accountsExists = YES;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) 
    return NO;
  
  //XXX check here to see if a pref file exists.
  BOOL prefsExists = NO;
  
  // Might not hurt to check to see if the folders are in place.
  if (!prefsExists)
  {
    nsCOMPtr<nsIMsgIncomingServer> localIncomingServer;
    nsCOMPtr<nsISupportsArray> accounts;
    rv = accountManager->GetAccounts(getter_AddRefs(accounts)); // Don't addref?
    if (NS_SUCCEEDED(rv))
    {
      PRUint32 numAccounts;
      accounts->Count(&numAccounts);
      if (numAccounts == 0)
      {
        shouldUpdatePrefs = YES;
        accountsExists = NO;
      }
      
      // Make sure the local folder server is intact.
      nsCOMPtr<nsIMsgIncomingServer> localFolderServer = nsnull;
      rv = accountManager->GetLocalFoldersServer(getter_AddRefs(localFolderServer));
      if (NS_FAILED(rv) || !localFolderServer)
      {
        rv = accountManager->GetLocalFoldersServer(getter_AddRefs(localIncomingServer));
        
        if (NS_FAILED(rv) || !localIncomingServer)
        {
          nsCOMPtr<nsIMessengerMigrator> messengerMigrator = do_GetService(NS_MESSENGERMIGRATOR_CONTRACTID, &rv);
          messengerMigrator->CreateLocalMailAccount(PR_FALSE);  // we aren't migrating.
          shouldUpdatePrefs = YES;
        }
      }
      // If we only have one account, make sure it isn't the local folders server
      else if (numAccounts == 1 && localFolderServer)
      {
        nsCOMPtr<nsISupports> supportsPrim = accounts->ElementAt(0);
        nsCOMPtr<nsIMsgAccount> msgAccount = do_QueryInterface(supportsPrim);
        if (msgAccount)
        {
          accountManager->GetLocalFoldersServer(getter_AddRefs(localIncomingServer));
          nsCOMPtr<nsIMsgIncomingServer> firstIncomingServer;
          msgAccount->GetIncomingServer(getter_AddRefs(firstIncomingServer));
          
          if (localIncomingServer == firstIncomingServer)
            accountsExists = NO;
        }
      }
    }
    else
      shouldUpdatePrefs = YES;
    
    // Create the prefs.
    if (shouldUpdatePrefs)
    {
      nsCOMPtr<nsIMessengerMigrator> messengerMigrator = do_GetService(NS_MESSENGERMIGRATOR_CONTRACTID, &rv);
      messengerMigrator->UpgradePrefs();
    }
  }
  
  return accountsExists;
}

-(BOOL)createAccount:(MessageAccount*)aMessageAccount
{
  nsresult rv;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, NO);
  
  nsCOMPtr<nsIMsgIdentity> identity;
  rv = accountManager->CreateIdentity(getter_AddRefs(identity));
  NS_ENSURE_SUCCESS(rv, NO);

  identity->SetEmail([[aMessageAccount emailAddress] cString]);
  identity->SetFullName([[aMessageAccount fullName] createNewUnicodeBuffer]);
  
  nsCOMPtr<nsIMsgIncomingServer> incomingServer;
  rv = accountManager->CreateIncomingServer([[aMessageAccount incomingServerUserName] cString],
                                            [[aMessageAccount incomingServerName] cString],
                                            [self literalForServerType:[aMessageAccount incomingServerType]], // pop3, etc.
                                            getter_AddRefs(incomingServer));
  NS_ENSURE_SUCCESS(rv, NO);
  
  incomingServer->SetPrettyName([[aMessageAccount accountName] createNewUnicodeBuffer]);
  // Mark the server as invalid until we assign it to the account.
  incomingServer->SetValid(PR_FALSE);
  
  nsCOMPtr<nsIMsgAccount> account;
  rv = accountManager->CreateAccount(getter_AddRefs(account));
  NS_ENSURE_SUCCESS(rv, NO);
  
  account->SetIncomingServer(incomingServer);
  account->AddIdentity(identity);
  
  incomingServer->SetValid(PR_TRUE);
  
  // Now setup the outgoing server, for now just worry about SMTP support.
  if ([aMessageAccount outgoingServerType] == eSMTP)
  {
    nsCOMPtr<nsISmtpService> smtpService = do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, NO);
    
    nsCOMPtr<nsISmtpServer> smtpServer;
    smtpService->CreateSmtpServer(getter_AddRefs(smtpServer));
    NS_ENSURE_SUCCESS(rv, NO);
    
    smtpServer->SetHostname([[aMessageAccount outgoingServerName] cString]);
    smtpServer->SetUsername([[aMessageAccount outgoingServerUserName] cString]);
    
    //XXX for now make this the default SMTP server, this will require some additional hacking
    //    to check for existing SMTP servers, and so on.
    smtpService->SetDefaultServer(smtpServer);
  }
  
  rv = accountManager->SaveAccountInfo();
  if (NS_FAILED(rv))
    NSLog(@"Problem with SaveAccountInfo");
  
  // Notify observers.
  [[NSNotificationCenter defaultCenter] postNotificationName:kAccountRegistryChanged object:nil];
  
  return YES;
}

-(BOOL)removeMsgAccount:(nsIMsgAccount*)aMessageAccount
{
  if (!aMessageAccount)
    return NO;
  
  nsresult rv;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, NO);
  
  rv = accountManager->RemoveAccount(aMessageAccount);
  NS_ENSURE_SUCCESS(rv, NO);

  accountManager->SaveAccountInfo();
  // Notify observers.
  [[NSNotificationCenter defaultCenter] postNotificationName:kAccountRegistryChanged object:nil];
  
  return YES;
}

-(BOOL)setDefaultMsgAccount:(nsIMsgAccount*)aMessageAccount
{
  if (!aMessageAccount)
    return NO;
  
  nsresult rv;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, NO);
  
  rv = accountManager->SetDefaultAccount(aMessageAccount);
  NS_ENSURE_SUCCESS(rv, NO);
  
  accountManager->SaveAccountInfo();
  
  return YES;
}

-(void)saveAccounts
{
  nsresult rv;
  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  if (NS_SUCCEEDED(rv))
    accountManager->SaveAccountInfo();
}

-(BOOL)userNeedsToAuth
{
  nsresult rv;
  PRBool needsToAuth = PR_FALSE;

  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
  if (NS_SUCCEEDED(rv))
    accountManager->GetUserNeedsToAuthenticate(&needsToAuth);
  
  return needsToAuth;
}

-(NSArray*)smtpServerList
{
  nsresult rv;
  NSMutableArray* serverList = nil;
  nsCOMPtr<nsISmtpService> smtpService = do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, nil);
  
  nsCOMPtr<nsISupportsArray> serversArr;
  rv = smtpService->GetSmtpServers(getter_AddRefs(serversArr));
  NS_ENSURE_SUCCESS(rv, nil);
  
  PRUint32 smtpArrSize, i = 0;
  rv = serversArr->Count(&smtpArrSize);
  if (NS_FAILED(rv) || smtpArrSize == 0)
    return nil;
  
  serverList = [[NSMutableArray alloc] init];
  for (; i < smtpArrSize; i++)
  {
    nsCOMPtr<nsISmtpServer> smtpServer = do_QueryInterface(serversArr->ElementAt(i), &rv);
    if (NS_FAILED(rv))
      continue;
    
    SmtpServerItem* serverItem = [[SmtpServerItem alloc] initWithSmtpServer:smtpServer];
    [serverList addObject:serverItem];
    [serverItem release];
  }
  
  return serverList;
}

-(SmtpServerItem*)defaultSmtpServerItem
{
  nsresult rv;
  SmtpServerItem* serverItem = nil;
  nsCOMPtr<nsISmtpService> smtpService = do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, nil);
  
  nsCOMPtr<nsISmtpServer> defaultSmtpServer;
  rv = smtpService->GetDefaultServer(getter_AddRefs(defaultSmtpServer));
  NS_ENSURE_SUCCESS(rv, nil);
  
  serverItem = [[SmtpServerItem alloc] initWithSmtpServer:defaultSmtpServer];
  return [serverItem autorelease];
}

-(SmtpServerItem*)defaultSmtpServerItemForIdentity:(nsIMsgIdentity*)aMsgIdentity
{
  nsresult rv;
  SmtpServerItem* serverItem = nil;
  nsCOMPtr<nsISmtpService> smtpService = do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, nil);
  
  nsXPIDLCString identitySmtpKey;
  rv = aMsgIdentity->GetSmtpServerKey(getter_Copies(identitySmtpKey));
  NS_ENSURE_SUCCESS(rv, nil);
  
  nsCOMPtr<nsISmtpServer> smtpServer;
  rv = smtpService->GetServerByKey(identitySmtpKey, getter_AddRefs(smtpServer));
  // If we didn't find the server, or the key hasn't been set to the message
  // identity yet, return the default SMTP server.
  if (NS_FAILED(rv) || !smtpServer)
    return [self defaultSmtpServerItem];
  
  serverItem = [[SmtpServerItem alloc] initWithSmtpServer:smtpServer];
  return [serverItem autorelease];
}

-(const char*)literalForServerType:(EAccountType)aServerType
{
  switch (aServerType)
  {
    case ePOP3:
      return "pop3";
    case eSMTP:
      return "smtp";
    case eIMAP:
      return "imap";
    case eOtherType:
      return "other";
    default:
      return "unkown";
  }
}

@end

#pragma mark - 

@implementation SmtpServerItem

-(id)initWithSmtpServer:(nsISmtpServer*)aSmtpServer
{
  if ((self = [super init]))
  {
    mSmtpServerRef = aSmtpServer;
    mDescription = nil;
    mServerName = nil;
    mUsername = nil;
    mPortNum = 0;
    mSocketType = 0;
    mUseAuthentication = NO;
    
    if (mSmtpServerRef)
    {
      nsresult rv;
      nsCAutoString description;
      rv = mSmtpServerRef->GetDescription(description);
      if (NS_SUCCEEDED(rv))
        mDescription = [[NSString stringWith_nsACString:description] retain];
      
      nsXPIDLCString hostname;
      rv = mSmtpServerRef->GetHostname(getter_Copies(hostname));
      if (NS_SUCCEEDED(rv))
        mServerName = [[NSString stringWithCString:hostname] retain];
      
      PRInt32 portNum;
      rv = mSmtpServerRef->GetPort(&portNum);
      if (NS_SUCCEEDED(rv))
        mPortNum = portNum;
      
      PRInt32 authMethod;
      rv = mSmtpServerRef->GetAuthMethod(&authMethod);
      if (NS_SUCCEEDED(rv))
        mUseAuthentication = authMethod;
      
      nsXPIDLCString username;
      rv = mSmtpServerRef->GetUsername(getter_Copies(username));
      if (NS_SUCCEEDED(rv))
        mUsername = [[NSString stringWithCString:username] retain];
      
      PRInt32 trySSLValue;
      rv = mSmtpServerRef->GetTrySSL(&trySSLValue);
      if (NS_SUCCEEDED(rv))
        mSocketType = trySSLValue;
    }
  }
  
  return self;
}

-(void)dealloc
{
  if (mDescription)
    [mDescription release];
  
  if (mServerName)
    [mServerName release];
  
  if (mUsername)
    [mUsername release];
  
  [super dealloc];
}

-(nsISmtpServer*)smtpServer
{
  return mSmtpServerRef;
}

-(NSString*)displayName
{
  nsresult rv;
  BOOL isDefaultServer = NO;
  nsXPIDLCString displayName;
  mSmtpServerRef->GetDisplayname(getter_Copies(displayName));
  
  nsXPIDLCString hostName;
  mSmtpServerRef->GetHostname(getter_Copies(hostName));
  
  
  nsCOMPtr<nsISmtpService> smtpService = do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv);
  if (NS_SUCCEEDED(rv))
  {
    nsCOMPtr<nsISmtpServer> defaultSmtpServer;
    rv = smtpService->GetDefaultServer(getter_AddRefs(defaultSmtpServer));
    if (NS_SUCCEEDED(rv) && defaultSmtpServer == mSmtpServerRef)
      isDefaultServer = YES;
  }
  
  NSString* returnVal = [NSString stringWithFormat:@"%s - %s", (const char*)displayName, (const char*)hostName];
  
  if (isDefaultServer)
    returnVal = [returnVal stringByAppendingString:NSLocalizedString(@"(Default)", nil)];
  
  return returnVal;
}

-(void)setDescription:(NSString*)aDescription
{
  if (mDescription)
    [mDescription release];
  
  mDescription = [aDescription retain];
}

-(void)setServerName:(NSString*)aServerName
{
  if (mServerName)
    [mServerName release];
  
  mServerName = [aServerName retain];
}

-(void)setUsername:(NSString*)aUsername
{
  if (mServerName)
    [mServerName release];
  
  mServerName = [aUsername retain];
}

-(void)setPortNum:(unsigned int)aPortNum
{
  mPortNum = aPortNum;
}

-(void)setSocketType:(unsigned int)aSocketType
{
  mSocketType = aSocketType;
}

-(void)setUseAuthentication:(BOOL)inShouldUseAuth
{
  mUseAuthentication = inShouldUseAuth;
}

-(NSString*)description
{
  if (!mDescription)
    return @"<nost specified>";
  
  return mDescription;
}

-(NSString*)serverName
{
  if (!mServerName)
    return @"<nost specified>";
  
  return mServerName;
}

-(NSString*)username
{
  if (!mUsername)
    return @"";
  
  return mUsername;
}

-(unsigned int)portNum
{
  return mPortNum;
}

-(unsigned int)socketType
{
  return mSocketType;
}

-(BOOL)useAuthentication
{
  return mUseAuthentication;
}

-(void)saveSettings
{
  if (!mSmtpServerRef)
    return;
  
  if (mDescription)
  {
    /**
     * In order to save the description, someone needs
     * to complete the implemenation for |assignTo_nsACString:|
     */
  }
  
  if (mServerName)
    mSmtpServerRef->SetHostname([mServerName cString]);
  
  if (mUsername)
    mSmtpServerRef->SetUsername([mUsername cString]);
  
  mSmtpServerRef->SetPort(mPortNum);
  mSmtpServerRef->SetAuthMethod((mUseAuthentication ? 1 : 0));
  mSmtpServerRef->SetTrySSL(mSocketType);
}

@end
